package com.wn.ziroom.interceptor;

import com.wn.utils.CookieUtils;
import com.wn.utils.JwtUtils;
import com.wn.ziroom.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class AjaxLoginInterceptor implements HandlerInterceptor {

    private StringRedisTemplate redisTemplate;

    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //-- 从cookie中取出Token
        String token = CookieUtils.getCookie("token",request);
        //-- 判断Cookie中是否有如果token不存在直接登录
        if(Objects.isNull(token)){
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print("201");
            return false;
        }

        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        String redisValue = opsForValue.get(token);

        //--  验证Redis的过期！
        //-- 只要浏览器不关闭 Cookie中会一直有token.(这个token能不能用是另外一回事)
        //-- 验证redis中是否有这个键.如果redis中没有，相当于长token过期了。要登录
        if (Objects.isNull(redisValue)){
            //-- 代表键过期了
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print("201");
            return false;
        }

        //-- 验证token是否有被篡改
        User user = JwtUtils.verifyTokenWithoutVerifyExp(token, User.class);
        if (Objects.isNull(user)){
            //-- 代表redis被篡改了。登录
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print("201");
            return false;
        }

        //-- 验证JWT层面是否过期
        User user1 = JwtUtils.verifyToken(redisValue, User.class);
        if (Objects.isNull(user1)){
            //-- 代表JWT过期了 redis的value要续签！
            String newToken = JwtUtils.createToken(user,10*60 * 1000);
            opsForValue.set(token,newToken,20 * 60 * 1000, TimeUnit.MILLISECONDS);
            System.out.println("续签-----------------------------------------");
        }

        //-- Redis 过期  被篡改，Cookie没有token 都要去登录！
        //-- JWT没有 过期  Redis没有过期  JWT没有被篡改
        return true;


    }
}
